package libra.startup;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.FilterRegistration.Dynamic;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import libra.servletPlugins.unAnno.MyFilter;
import libra.servletPlugins.unAnno.MyListener;
import libra.servletPlugins.unAnno.MyServlet;

/**
 * web容器启动的时候创建对象,调用方法来初始化容器以及前端控制器
 * @author libra
 */
public class SpringMvcInit extends AbstractAnnotationConfigDispatcherServletInitializer {
	// 获取根容器配置类：(Spring的配置文件)父容器,可以不配置父容器,将所有组件放入ServletConfig
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return null;
	}
	// 获取web容器的配置类：(SpringMVC配置文件)子容器
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] { WebConfig.class };
	}
	// 获取DispatcherServlet的映射信息
	@Override
	protected String[] getServletMappings() {
		/*
		 * '/'拦截所有,包括静态资源,不包括*.jsp
		 * '/*'拦截所有,包括静态资源,包括*.jsp
		 */
		return new String[] {"/"};
	}
	
	// 项目启动触发,添加监听器,一定要调用super的父调用
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		// 系统启动时注册Servlet
		Servlet myServlet = new MyServlet();
		ServletRegistration myServletRegistration = servletContext.addServlet("myServlet", myServlet);
		myServletRegistration.addMapping("/myServlet");
		
		// 系统启动时注册listener
		ServletContextListener myListener = new MyListener();
		servletContext.addListener(myListener);
		
		// 系统启动时注册filter
        FilterRegistration myFilter = servletContext.addFilter("myFilter", MyFilter.class);
        // 设置init param, param可以从properties文件中读取或其他方式获取，提供一个想法
//        sysFilter.setInitParameter("specialUrl", "/login,/register");
//        sysFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), true, "/*");  
        myFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, new String[] {"/annoServlet","/myServlet"} );  
		
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter("UTF-8");
        FilterRegistration encodeFilter = servletContext.addFilter("encodeFilter", characterEncodingFilter);
        encodeFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");  
        
		super.onStartup(servletContext);
	}
	
	@Override
	protected Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {
		return super.registerServletFilter(servletContext, filter);
	}
	
}